import {
  USER_ADDRESS_SAVE,
  USER_ADDRESS_UPDATEADDRESS,
  USER_DORM_ID,
  USER_DORM_VERIFYNAME,
} from "../../messages/uris";
import req from "../../utils/request";
import WxValidate from "../../utils/WxValidate.js";
// pages/adsfas.js
Page({
  mixins: [require("../../mixin/themeChanged")],

  /**
   * 页面的初始数据
   */
  data: {
    address: {
      addressId: null, //地址id
      dormAddress: "", //宿舍地址
      dormCode: "", //宿舍号
      addressName: "", //收件人
      addressPhone: "", //收件人号码
      isDefault: 1, //是否默认默认
      isDefault02: false, //是否默认默认
      currentValue: "",
      isCurrentWaring: false, 
      //弹出层
      topTips: false,
      hide: false,
      tipValue: "",
    },
    result: [],
    schoolName: "",
  },
  onCurrentInput(evt) {
    const { currentValue } = evt.detail;
    this.setData({
      isCurrentWaring: true,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    if (options.address) {
      var updateAddress = JSON.parse(options.address);
      var isDefault02Str = "address.isDefault02";
      if (updateAddress.isDefault == 1) {
        that.setData({
          address: updateAddress,
          [isDefault02Str]: true,
        });
      } else {
        that.setData({
          address: updateAddress,
          [isDefault02Str]: false,
        });
      }
    }

    that.initValidate(); //验证规则函数
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (option) {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  //表单提交方法
  formSubmit(e) {
    var addressParam = e.detail.value;
    if (!this.WxValidate.checkForm(addressParam)) {
      const error = this.WxValidate.errorList[0];
      this.showModal(error);
      return false;
    }
    this.verifyDormAddress(addressParam);
  },

  //保存方法
  save: function (addressParam) {
    const that = this;
    req.post(
      USER_ADDRESS_SAVE,
      addressParam,
      (resp) => {
        wx.showToast({
          title: "保存地址成功",
          icon: "", //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
          duration: 2000, //停留时间
        });
        wx.navigateBack({
          //返回上一页
          delta: 1,
        });
      },
      (resp) => {
        wx.showToast({
          title: "保存地址失败",
          icon: "", //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
          duration: 2000, //停留时间
        });
      },
      (res) => {},
      that
    );
  },

  //修改方法
  update: function (addressParam) {
    const that = this;
    req.post(
      USER_ADDRESS_UPDATEADDRESS,
      addressParam,
      (resp) => {
        wx.showToast({
          title: "修改地址成功",
          icon: "", //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
          duration: 2000, //停留时间
        });
        wx.navigateBack({
          //返回上一页
          delta: 1,
        });
      },
      (resp) => {
        wx.showToast({
          title: "修改地址失败",
          icon: "", //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
          duration: 2000, //停留时间
        });
      },
      (res) => {},
      that
    );
  },

  //判断宿舍是否合法
  verifyDormAddress: function (addressParam) {
    //根据地址id判断是保存操作还是修改操作
    const that = this;
    req.get(
      USER_DORM_VERIFYNAME + "?dormName=" + addressParam.dormAddress,
      {},
      (resp) => {
        if (that.data.address.addressId == null) {
          //保存
          that.save(addressParam);
        } else {
          //修改
          that.update(addressParam);
        }
      },
      (resp) => {
        wx.showToast({
          title: "请输入正确宿舍",
          icon: "", //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
          duration: 2000, //停留时间
        });
      },
      (res) => {},
      that
    );
  },

  //获取checkbox  更改状态
  getIsDefault: function () {
    const that = this;
    var isDefault02 = that.data.address.isDefault02;
    var isDefaultStr = "address.isDefault";
    var isDefault02Str = "address.isDefault02";
    if (isDefault02 == false) {
      that.setData({
        [isDefaultStr]: 1,
        [isDefault02Str]: true,
      });
    } else {
      that.setData({
        [isDefaultStr]: 0,
        [isDefault02Str]: false,
      });
    }
  },

  /**--------------宿舍下拉框选项-------------------- */
  searchWells: function (e) {
    var name = e.detail.value;
    if (name != "") {
      req.get(
        USER_DORM_ID + "?schoolId=" + 1008611,
        {},
        (resp) => {
          console.log(resp);
          if (resp.data.result != null) {
            var val = resp.data.result;
            var result = new Array();
            if (name != "" && val != null) {
              //判断用户输入搜素不为空时执行下面的代码
              for (var i = 0; i < val.length; i++) {
                var good = val[i];
                if (good.indexOf(name) > -1) {
                  result.push(good);
                }
              }
              this.setData({ result: result });
            }
          }
        },
        (resp) => {
          console.log("查询失败");
        },
        (res) => {},
        that
      );
    } else {
      this.resetSearch();
    }
  },

  //当用户输入字符后点击恢复默认状态
  resetSearch: function () {
    var result = new Array();
    var dormAddressStr = "address.dormAddress";
    this.setData({ result: result, [dormAddressStr]: "" });
  },

  //设置选择的学校
  getSchoolName: function (e) {
    var dormAddress = e.currentTarget.dataset.index;
    var dormAddressStr = "address.dormAddress";
    const that = this;
    that.setData({
      [dormAddressStr]: dormAddress,
      result: null,
    });
  },
  /**----------------表单验证------------------ */

  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    });
  },

  //验证函数
  initValidate() {
    const rules = {
      dormAddress: {
        required: true,
        minlength: 2,
        maxlength: 6,
      },
      dormCode: {
        required: true,
        minlength: 3,
        maxlength: 5,
      },
      addressName: {
        required: true,
        minlength: 2,
        maxlength: 6,
      },
      addressPhone: {
        required: true,
        tel: true,
      },
    };
    const messages = {
      dormAddress: {
        required: "请填写宿舍",
        minlength: "请输入正确的宿舍",
        maxlength: "请输入正确的宿舍",
      },
      dormCode: {
        required: "请填写详细地址",
        minlength: "请输入正确的详细地址",
        maxlength: "请输入正确的详细地址",
      },
      addressName: {
        required: "请填写收件人姓名",
        minlength: "请输入正确的收件人姓名",
        maxlength: "请输入正确的详细地址",
      },
      addressPhone: {
        required: "请填写手机号",
        tel: "请填写正确的手机号",
      },
    };
    this.WxValidate = new WxValidate(rules, messages);
  },
});
